<template>
  <div>
    <el-form :model="form">
      <el-form-item ref="uploadElement">
        <el-upload
          ref="upload"
          action=""
          accept="image/png,image/gif,image/jpg,image/jpeg"
          list-type="picture-card"
          :limit="limitNum"
          :auto-upload="false"
          :before-upload="handleBeforeUpload"
          :on-preview="handlePictureCardPreview"
          :on-remove="handleRemove"
          :on-change="imgChange"
          :class="{ hideshow: hideUpload }"
        >
          <i class="el-icon-plus"></i>
        </el-upload>
        <el-dialog :visible.sync="dialogVisible" append-to-body>
          <img width="100%" :src="dialogImageUrl" alt="" />
        </el-dialog>
      </el-form-item>
      <el-form-item>
        <el-button size="small" type="primary" @click="uploadFile"
          >立即上传</el-button
        >
      </el-form-item>
    </el-form>
  </div>
</template>

<script>
import { postSetIcon } from "../assets/js/api";
export default {
  data() {
    return {
      hideUpload: false,
      dialogImageUrl: "",
      dialogVisible: false, //图片预览弹窗
      limitNum: 1,
      form: {},
      dialogVisible2: false, //弹窗
    };
  },
  methods: {
    formResetFields(data) {
      if (data == true) {
        this.$refs.upload.clearFiles();
        this.hideUpload = false;
      }
    },
    // 上传文件之前的钩子
    handleBeforeUpload(file) {
      if (
        !(
          file.type === "image/png" ||
          file.type === "image/gif" ||
          file.type === "image/jpg" ||
          file.type === "image/jpeg"
        )
      ) {
        this.$notify.warning({
          title: "警告",
          message:
            "请上传格式为image/png, image/gif, image/jpg, image/jpeg的图片",
        });
      }
      let fd = new FormData();
      fd.append(" icon", file);
      postSetIcon(fd).then((res) => {
        if (res.code == 200) {
          this.$message.success("修改成功");
          this.$emit("messageData", res.data);
        }
      });
    },
    // 文件列表移除文件时的钩子
    handleRemove(file, fileList) {
      this.hideUpload = fileList.length >= this.limitNum;
    },
    // 点击文件列表中已上传的文件时的钩子
    handlePictureCardPreview(file) {
      this.dialogImageUrl = file.url;
      this.dialogVisible = true;
    },
    uploadFile() {
      this.$refs.upload.submit();
    },
    imgChange(files, fileList) {
      (files, fileList.length);
      this.showUlpoad = false;
      this.hideUpload = fileList.length >= this.limitNum;
      if (fileList) {
        this.$refs.uploadElement.clearValidate();
      }
    },
  },
};
</script>

<style type="less">
.hideshow .el-upload--picture-card {
  display: none;
}
</style>
<style scoped type="less">
::v-deep .el-form-item__content {
  text-align: center;
}
</style>